//
//  MYTabBar.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-20.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYTabBar.h"
#import "MYTabBarButton.h"
@interface MYTabBar ()
@property (nonatomic, weak) UIButton *addButton;
@property (nonatomic, weak) MYTabBarButton *selectedButton;//当前选中按钮
@property (nonatomic, strong) NSMutableArray *tabBarButtons;
@end
@implementation MYTabBar
#pragma mark - 添加加号按钮addButton
- (UIButton *)addButton
{
    if (nil == _addButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setNormalBg:@"tabbar_compose_button" highlightedBg:@"tabbar_compose_button_highlighted"];
        [btn setNormalImage:@"tabbar_compose_icon_add" highlightedImage:@"tabbar_compose_icon_add_highlighted"];
        [btn addTarget:self action:@selector(addButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn sizeToFit];//自动算出控件最合适的尺寸
        [self addSubview:btn];
        self.addButton = btn;
    }
    return _addButton;
}
- (void)addButtonClick:(UIButton *)btn
{
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickaddButton:)]) {
        [self.delegate tabBarDidClickaddButton:self];
    }
}
- (NSMutableArray *)tabBarButtons
{
    if (nil == _tabBarButtons) {
        _tabBarButtons = [NSMutableArray array];
    }
    return _tabBarButtons;
}
// 添加TabBarButton
- (void)addTabBarButton:(UITabBarItem *)item
{
    MYTabBarButton *btn = [MYTabBarButton buttonWithType:UIButtonTypeCustom];
    btn.item = item;
    btn.tag = self.subviews.count;
    [btn addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDown];
    if (0 == btn.tag) {
        [self tabBarButtonClick:btn];
    }
    [self addSubview:btn];
    [self.tabBarButtons addObject:btn];
}
#pragma mark - tabBarButtonClick点击事件
- (void)tabBarButtonClick:(MYTabBarButton *)btn
{
    self.selectedButton.selected = NO;
    btn.selected = YES;
    self.selectedButton = btn;
    self.operateBlock(btn.tag);
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    //设置所有tabBarButton的frame
    [self setupAllTabBarButtonFrame];
    //设置加号按钮的frame
    [self setupAddButtonFrame];
}
#pragma mark - 设置所有tabBarButton的frame
- (void)setupAllTabBarButtonFrame
{
    NSUInteger count = self.tabBarButtons.count + 1;
    CGFloat w = self.width / count;
    CGFloat h = self.height;
    CGFloat y = 0;
    __block CGFloat x = 0;
    [self.tabBarButtons enumerateObjectsUsingBlock:^(MYTabBarButton *button, NSUInteger idx, BOOL *stop) {
        if (idx >= (count - 1) / 2) {
            idx++;
        }
        x = idx * w;
        button.frame = CGRectMake(x, y, w, h);
    }];
}
#pragma mark - 设置加号按钮的frame
- (void)setupAddButtonFrame
{
    CGFloat x = self.width * 0.5;
    CGFloat y = self.height * 0.5;
    self.addButton.center = CGPointMake(x, y);
}
@end
